package com.im.business.history.kafka;

import com.alibaba.fastjson.JSONObject;
import com.im.business.history.service.GroupMessageService;
import com.im.business.history.service.SingleMessageService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @Created leijun
 * @Date 2021/10/27 7:07 上午
 */
@Component
public class KafkaConsumer {

    @Autowired
    private SingleMessageService singleMessageService;
    @Autowired
    private GroupMessageService groupMessageService;

    /**
     * 监听单聊消息、群聊消息topic
     * @param record
     */
    @KafkaListener(topics = {"single_message", "group_message"})
    public void onMessage(ConsumerRecord<?, ?> record) {
        String topic = record.topic();
        System.out.println("【业务层】接收到kafka topic【"+topic+"】消息："+record.value());
        JSONObject message = JSONObject.parseObject(record.value().toString());
        if (topic.equals("single_message")) {
            singleMessageService.saveSingleMessage(message);
        } else if (topic.equals("group_message")) {
            groupMessageService.saveGroupMessage(message);
        }
    }
}
